<template>
  <div class="model">
    <input type="file"
           name="file"
           id="file"
           @change="inputChange($event)">
    <!-- <input ref="pathClear"
           class="fileImage"
           type="file"
           @change="inputChange($event)" /> -->
    <button id="upload"
            @click="upload()">upload</button>
  </div>
</template>

<script>
export default {
  name: 'model',
  // 实例的数据对象
  data () {
    return {
      msg: 'model',
      file: []
    }
  },
  // created:在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图。
  created () {

  },
  // 方法
  methods: {
    inputChange (event) {
      var img1 = event.target.files[0]
      this.file = img1
    },
    async upload () {
      var storage = window.localStorage
      console.log('start1:', storage['fileStart'], '    inedx1:', storage['fileIndex'])
      var blob = this.file
      var bytesPerPiece = 1024 * 1024 * 5 // 每个文件切片大小定为1MB .
      var start = 0
      var end = 0
      var index = 0
      // 总大小
      var filesize = blob.size
      // 文件名
      var filename = blob.name
      // 总页数
      var totalPieces = Math.ceil(filesize / bytesPerPiece)

      // 发送一个post请求携带fileName 到后台，后台判断该文件是否上传完毕，
      var isFlag = true
      if (isFlag === false) {
        start = parseInt(storage['fileStart'])
        index = parseInt(storage['fileIndex'])
      }
      // if (filename === 'JavaScript高级程序设计（第3版）非扫描版 - 副本.mp4') {
      //   if (storage['fileIndex'] === undefined) {
      //     start = 0
      //     end = 0
      //     index = 0
      //   }
      // }
      while (start < filesize) {
        end = start + bytesPerPiece
        if (end > filesize) {
          end = filesize
        }
        var chunk = blob.slice(start, end)
        var formData = new FormData()
        formData.append('id', 'WU_FILE_01')
        formData.append('name', filename)
        formData.append('size', filesize)
        formData.append('chunks', totalPieces)
        formData.append('chunk', index)
        formData.append('file', chunk)
        if (index === totalPieces - 1) {
          formData.append('needMerge', true)
        }
        var url = 'api/fileupload.php'
        await this.axios.post(url, formData).then((res) => {
          if (res.data.id !== undefined) {
            storage['fileName'] = filename
            storage['fileStart'] = start
            storage['fileIndex'] = index
            console.log('start2:', start, '    inedx2:', index)
          }
        })
        start = end
        index++
      }
    }
  },
  // 侦听器，监测Vue实例上的数据变动
  watch: {

  },
  // mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作。
  mounted () {
  }
}
</script>

<style scoped>
</style>
